package api

import (
	"gateway/basic/config"
	user "gateway/basic/proto/userproto"
	"gateway/handler/request"
	"gateway/handler/response"
	"gateway/websocket"
	"github.com/gin-gonic/gin"
	"log"
	"strconv"
)

func GetSwipeCandidates(c *gin.Context) {
	userId := c.GetUint64("userId")
	if userId == 0 {
		response.ParameterError(c, "用户未登录", nil)
		return
	}
	var req request.GetSwipeCandidatesReq
	if err := c.ShouldBindQuery(&req); err != nil {
		response.ParameterError(c, "参数格式错误: "+err.Error(), nil)
		return
	}
	if req.Limit <= 0 {
		req.Limit = 10
	}
	if req.Limit > 50 {
		req.Limit = 50
	}
	res, err := config.UserClient.GetSwipeCandidates(c, &user.GetSwipeCandidatesReq{
		UserId: userId,
		Limit:  int32(req.Limit),
	})
	if err != nil {
		log.Printf("GetSwipeCandidates: %v", err)
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, "获取候选用户成功", res)
}

func SwipeAction(c *gin.Context) {
	userId := c.GetUint64("userId")
	if userId == 0 {
		response.ParameterError(c, "用户未登录", nil)
		return
	}
	var req request.SwipeActionReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数格式错误: "+err.Error(), nil)
		return
	}
	if req.Action != 1 && req.Action != 2 {
		response.ParameterError(c, "滑动动作无效(1-左滑,2-右滑)", nil)
		return
	}
	res, err := config.UserClient.SwipeAction(c, &user.SwipeActionReq{
		UserId:   userId,
		TargetId: req.TargetId,
		Action:   int32(req.Action),
	})
	if err != nil {
		log.Printf("SwipeAction: %v", err)
		response.SrvError(c, err.Error(), nil)
		return
	}
	if res.IsMatch {
		// 将 uint64 转为 string 用于 WebSocket
		userIdStr := strconv.FormatUint(userId, 10)
		targetIdStr := strconv.FormatUint(req.TargetId, 10)

		targetUserRes, err := config.UserClient.UserDetail(c, &user.UserDetailReq{Id: req.TargetId})
		if err == nil {
			matchData := &websocket.MatchSuccessData{
				MatchId:    res.MatchId,
				UserId:     targetIdStr,
				NickName:   targetUserRes.NickName,
				Avatar:     "",
				MatchScore: 0.85,
				Reason:     res.Message,
			}
			websocket.WsManager.SendMatchSuccess(userIdStr, matchData)
		}
		currentUserRes, _ := config.UserClient.UserDetail(c, &user.UserDetailReq{Id: userId})
		if currentUserRes != nil {
			matchDataForTarget := &websocket.MatchSuccessData{
				MatchId:    res.MatchId,
				UserId:     userIdStr,
				NickName:   currentUserRes.NickName,
				Avatar:     "",
				MatchScore: 0.85,
				Reason:     res.Message,
			}
			websocket.WsManager.SendMatchSuccess(targetIdStr, matchDataForTarget)
		}
		response.Success(c, res.Message, gin.H{"is_match": res.IsMatch, "match_id": res.MatchId, "message": res.Message})
	} else {
		response.Success(c, res.Message, gin.H{"is_match": res.IsMatch, "message": res.Message})
	}
}

func GetMatchList(c *gin.Context) {
	userId := c.GetUint64("userId")
	if userId == 0 {
		response.ParameterError(c, "用户未登录", nil)
		return
	}
	var req request.GetMatchListReq
	if err := c.ShouldBindQuery(&req); err != nil {
		response.ParameterError(c, "参数格式错误: "+err.Error(), nil)
		return
	}
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 20
	}
	if req.PageSize > 100 {
		req.PageSize = 100
	}
	res, err := config.UserClient.GetMatchList(c, &user.GetMatchListReq{
		UserId:   userId,
		Page:     int32(req.Page),
		PageSize: int32(req.PageSize),
	})
	if err != nil {
		log.Printf("GetMatchList: %v", err)
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, "获取匹配列表成功", res)
}

func Unmatch(c *gin.Context) {
	userId := c.GetUint64("userId")
	if userId == 0 {
		response.ParameterError(c, "用户未登录", nil)
		return
	}
	var req request.UnmatchReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数格式错误: "+err.Error(), nil)
		return
	}
	res, err := config.UserClient.Unmatch(c, &user.UnmatchReq{
		UserId:  userId,
		MatchId: req.MatchId,
	})
	if err != nil {
		log.Printf("Unmatch: %v", err)
		response.SrvError(c, err.Error(), nil)
		return
	}
	if res.Success {
		response.Success(c, res.Message, nil)
	} else {
		response.SrvError(c, res.Message, nil)
	}
}
